<template>
  <div class="app-container">
    <el-card>
      <div style="display:flex; gap:8px; align-items:center; margin-bottom:12px">
        <el-input v-model="query.deviceName" placeholder="设备名称" clearable style="width:200px" />
        <el-input v-model="query.deviceCode" placeholder="设备编码" clearable style="width:200px" />
        <el-select v-model="query.productId" placeholder="选择产品" clearable style="width:200px">
          <el-option
            v-for="product in productOptions"
            :key="product.productId"
            :label="product.productName"
            :value="product.productId"
          />
        </el-select>
        <el-tree-select
          v-model="query.groupId"
          :data="groupOptions"
          :props="{ value: 'groupId', label: 'groupName', children: 'children' }"
          placeholder="选择分组"
          clearable
          check-strictly
          style="width:200px"
        />
        <el-select v-model="query.deviceStatus" placeholder="设备状态" clearable style="width:120px">
          <el-option label="在线" value="1" />
          <el-option label="离线" value="0" />
          <el-option label="故障" value="2" />
        </el-select>
        <el-button type="primary" @click="load">查询</el-button>
        <el-button @click="reset">重置</el-button>
        <el-button type="success" @click="openCreate">新增设备</el-button>
      </div>
      
      <el-table :data="rows" border stripe>
        <el-table-column prop="deviceName" label="设备名称" min-width="150" />
        <el-table-column prop="deviceCode" label="设备编码" min-width="120" />
        <el-table-column prop="productName" label="产品名称" min-width="120" />
        <el-table-column prop="deviceType" label="设备类型" min-width="100" />
        <el-table-column prop="groupName" label="设备分组" min-width="120" />
        <el-table-column prop="protocolType" label="协议类型" width="100" />
        <el-table-column prop="deviceIp" label="设备IP" width="120" />
        <el-table-column label="设备状态" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.deviceStatus === '1'" type="success">在线</el-tag>
            <el-tag v-else-if="row.deviceStatus === '0'" type="info">离线</el-tag>
            <el-tag v-else-if="row.deviceStatus === '2'" type="danger">故障</el-tag>
            <el-tag v-else type="info">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="location" label="设备位置" min-width="150" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="() => openEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="() => doRemove(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div style="margin-top:12px; text-align:right">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10,20,50,100]"
          v-model:current-page="query.pageNum"
          v-model:page-size="query.pageSize"
          :total="total"
          @size-change="load"
          @current-change="load"
        />
      </div>
    </el-card>

    <el-dialog v-model="dialog.visible" :title="dialog.isEdit ? '编辑设备' : '新增设备'" width="700px" @close="closeDialog">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-tabs v-model="deviceFormTab">
          <el-tab-pane label="基本信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="设备名称" prop="deviceName">
                  <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="设备编码" prop="deviceCode">
                  <el-input v-model="form.deviceCode" placeholder="请输入设备编码" />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="产品" prop="productId">
                  <el-input
                    v-model="selectedProductName"
                    placeholder="请选择产品"
                    readonly
                    @click="openProductSelector"
                    style="cursor: pointer"
                  >
                    <template #suffix>
                      <el-icon><Search /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="设备分组" prop="groupId">
                  <el-tree-select
                    v-model="form.groupId"
                    :data="groupOptions"
                    :props="{ value: 'groupId', label: 'groupName', children: 'children' }"
                    placeholder="请选择设备分组"
                    clearable
                    check-strictly
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="设备状态" prop="deviceStatus">
                  <el-select v-model="form.deviceStatus" placeholder="请选择设备状态" style="width: 100%">
                    <el-option label="在线" value="1" />
                    <el-option label="离线" value="0" />
                    <el-option label="故障" value="2" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="设备IP" prop="deviceIp">
                  <el-input v-model="form.deviceIp" placeholder="请输入设备IP" />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item label="设备位置" prop="location">
              <el-input v-model="form.location" placeholder="请输入设备位置" />
            </el-form-item>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="经度" prop="longitude">
                  <el-input-number v-model="form.longitude" placeholder="请输入经度" :precision="6" style="width: 100%" />
        </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="纬度" prop="latitude">
                  <el-input-number v-model="form.latitude" placeholder="请输入纬度" :precision="6" style="width: 100%" />
        </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item label="安装时间" prop="installTime">
              <el-date-picker
                v-model="form.installTime"
                type="datetime"
                placeholder="请选择安装时间"
                style="width: 100%"
              />
        </el-form-item>
            
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="通信方式" name="protocol">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="绑定规则" prop="flowId">
                  <el-input
                    v-model="selectedFlowName"
                    placeholder="请选择规则"
                    readonly
                    @click="openFlowSelector"
                    style="cursor: pointer"
                  >
                    <template #suffix>
                      <el-icon><Search /></el-icon>
                    </template>
                  </el-input>
        </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="通信协议" prop="protocolType">
                  <el-select v-model="form.protocolType" placeholder="继承产品(不选)或选择覆盖" clearable style="width: 100%">
                    <el-option label="MQTT" value="mqtt" />
                    <el-option label="TCP" value="tcp" />
                    <el-option label="TCP服务器" value="tcp-server" />
                    <el-option label="UDP服务器" value="udp-server" />
                    <el-option label="Modbus" value="modbus" />
                    <el-option label="HTTP" value="http" />
                    <el-option label="CoAP" value="coap" />
                  </el-select>
        </el-form-item>
              </el-col>
              <el-col :span="24" v-if="form.protocolType">
                <el-form-item label="协议覆盖(JSON)" prop="protocolConfigOverride">
                  <div style="display:flex; gap:8px; width:100%">
                    <el-input
                      v-model="form.protocolConfigOverride"
                      type="textarea"
                      :rows="6"
                      :placeholder="deviceProtocolJsonPlaceholder"
                    />
                    <el-button type="primary" @click="openDeviceProtoEditor">编辑</el-button>
                  </div>
        </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="doSubmit" :loading="buttonLoading">保存</el-button>
      </template>
    </el-dialog>

    <!-- 协议参数编辑对话框（设备覆盖） -->
    <el-dialog v-model="deviceProtoEditor.visible" title="编辑协议覆盖参数" width="700px">
      <template v-if="form.protocolType === 'mqtt'">
        <el-form label-width="120px">
          <el-form-item label="Broker URL"><el-input v-model="deviceProtoEditor.mqtt.brokerUrl" /></el-form-item>
          <el-form-item label="Client ID"><el-input v-model="deviceProtoEditor.mqtt.clientId" /></el-form-item>
          <el-form-item label="用户名"><el-input v-model="deviceProtoEditor.mqtt.username" /></el-form-item>
          <el-form-item label="密码"><el-input v-model="deviceProtoEditor.mqtt.password" type="password" /></el-form-item>
          <el-form-item label="发布主题"><el-input v-model="deviceProtoEditor.mqtt.publishTopic" /></el-form-item>
          <el-form-item label="订阅主题"><el-input v-model="deviceProtoEditor.mqtt.subscribeTopic" /></el-form-item>
          <el-form-item label="QoS"><el-input v-model.number="deviceProtoEditor.mqtt.qos" type="number" /></el-form-item>
        </el-form>
      </template>
      <template v-else-if="form.protocolType === 'modbus'">
        <el-form label-width="120px">
          <el-form-item label="类型">
            <el-select v-model="deviceProtoEditor.modbus.type" style="width:100%">
              <el-option label="TCP" value="tcp" />
              <el-option label="RTU" value="rtu" />
            </el-select>
          </el-form-item>
          <template v-if="deviceProtoEditor.modbus.type === 'tcp'">
            <el-form-item label="Host"><el-input v-model="deviceProtoEditor.modbus.host" /></el-form-item>
            <el-form-item label="Port"><el-input v-model.number="deviceProtoEditor.modbus.port" type="number" /></el-form-item>
            <el-form-item label="超时(ms)"><el-input v-model.number="deviceProtoEditor.modbus.timeoutMs" type="number" /></el-form-item>
          </template>
          <template v-else>
            <el-form-item label="串口名"><el-input v-model="deviceProtoEditor.modbus.portName" /></el-form-item>
            <el-form-item label="波特率"><el-input v-model.number="deviceProtoEditor.modbus.baudRate" type="number" /></el-form-item>
            <el-form-item label="数据位"><el-input v-model.number="deviceProtoEditor.modbus.dataBits" type="number" /></el-form-item>
            <el-form-item label="停止位"><el-input v-model.number="deviceProtoEditor.modbus.stopBits" type="number" /></el-form-item>
            <el-form-item label="校验"><el-input v-model.number="deviceProtoEditor.modbus.parity" type="number" /></el-form-item>
            <el-form-item label="超时(ms)"><el-input v-model.number="deviceProtoEditor.modbus.timeoutMs" type="number" /></el-form-item>
          </template>

          <!-- 新增：点位配置表 -->
          <el-divider>点位配置 (points)</el-divider>
          <div>
            <el-button type="primary" link @click="addModbusPoint">新增点位</el-button>
          </div>
          <el-table :data="deviceProtoEditor.modbus.points" size="small" border stripe style="margin-top:8px">
            <el-table-column label="code" min-width="140">
              <template #default="{ row }">
                <el-input v-model="row.code" placeholder="如 temperature" />
              </template>
            </el-table-column>
            <el-table-column label="function" width="140">
              <template #default="{ row }">
                <el-select v-model="row.function" style="width:120px">
                  <el-option label="holding" value="holding" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="slaveId" width="120">
              <template #default="{ row }">
                <el-input-number v-model="row.slaveId" :min="0" :step="1" />
              </template>
            </el-table-column>
            <el-table-column label="offset" width="120">
              <template #default="{ row }">
                <el-input-number v-model="row.offset" :min="0" :step="1" />
              </template>
            </el-table-column>
            <el-table-column label="quantity" width="120">
              <template #default="{ row }">
                <el-input-number v-model="row.quantity" :min="1" :step="1" />
              </template>
            </el-table-column>
            <el-table-column label="periodSec" width="140">
              <template #default="{ row }">
                <el-input-number v-model="row.periodSec" :min="1" :step="1" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="{ $index }">
                <el-button type="danger" link @click="removeModbusPoint($index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </template>
      <template v-else-if="form.protocolType === 'http'">
        <el-form label-width="120px">
          <el-form-item label="Base URL"><el-input v-model="deviceProtoEditor.http.baseUrl" /></el-form-item>
          <el-form-item label="Path"><el-input v-model="deviceProtoEditor.http.path" /></el-form-item>
          <el-form-item label="Method"><el-input v-model="deviceProtoEditor.http.method" /></el-form-item>
        </el-form>
      </template>
      <template v-else-if="form.protocolType === 'tcp'">
        <el-form label-width="120px">
          <el-form-item label="Host"><el-input v-model="deviceProtoEditor.tcp.host" /></el-form-item>
          <el-form-item label="Port"><el-input v-model.number="deviceProtoEditor.tcp.port" type="number" /></el-form-item>
          <el-form-item label="超时(ms)"><el-input v-model.number="deviceProtoEditor.tcp.timeoutMs" type="number" /></el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-button @click="deviceProtoEditor.visible = false">取消</el-button>
        <el-button type="primary" @click="applyDeviceProtoEditor">确定</el-button>
      </template>
    </el-dialog>

    <!-- 产品选择对话框 -->
    <el-dialog v-model="productSelector.visible" title="选择产品" width="800px">
      <div style="display:flex; gap:8px; align-items:center; margin-bottom:12px">
        <el-input v-model="productQuery.productName" placeholder="产品名称" clearable style="width:200px" />
        <el-input v-model="productQuery.productCode" placeholder="产品编码" clearable style="width:200px" />
        <el-select v-model="productQuery.deviceType" placeholder="设备类型" clearable style="width:150px">
          <el-option label="温度传感器" value="temperature" />
          <el-option label="压力传感器" value="pressure" />
          <el-option label="温湿度传感器" value="temperature_humidity" />
        </el-select>
        <el-button type="primary" @click="loadProducts">查询</el-button>
        <el-button @click="resetProductQuery">重置</el-button>
      </div>
      
      <el-table 
        :data="productRows" 
        border 
        stripe
        @row-click="selectProduct"
        style="cursor: pointer"
      >
        <el-table-column prop="productName" label="产品名称" min-width="150" />
        <el-table-column prop="productCode" label="产品编码" min-width="120" />
        <el-table-column prop="deviceType" label="设备类型" min-width="120" />
        <el-table-column prop="brand" label="品牌" min-width="100" />
        <el-table-column prop="specification" label="规格" min-width="120" />
        <el-table-column prop="price" label="价格" width="100">
          <template #default="{ row }">
            ¥{{ row.price || '0.00' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="selectProduct(row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div style="margin-top:12px; text-align:right">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10,20,50,100]"
          v-model:current-page="productQuery.pageNum"
          v-model:page-size="productQuery.pageSize"
          :total="productTotal"
          @size-change="loadProducts"
          @current-change="loadProducts"
        />
      </div>
      
      <template #footer>
        <el-button @click="productSelector.visible = false">取消</el-button>
      </template>
    </el-dialog>

    <!-- 规则选择对话框 -->
    <el-dialog v-model="flowSelector.visible" title="选择规则" width="800px">
      <div style="display:flex; gap:8px; align-items:center; margin-bottom:12px">
        <el-input v-model="flowQuery.flowName" placeholder="规则名称" clearable style="width:200px" />
        <el-button type="primary" @click="loadFlows">查询</el-button>
        <el-button @click="resetFlowQuery">重置</el-button>
      </div>
      
      <el-table 
        :data="flowRows" 
        border 
        stripe
        @row-click="selectFlow"
        style="cursor: pointer"
      >
        <el-table-column prop="flowName" label="规则名称" min-width="200" />
        <el-table-column prop="flowDescription" label="描述" min-width="260" />
        <el-table-column prop="isActive" label="是否激活" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isActive ? 'success' : 'info'">{{ row.isActive ? '是' : '否' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="selectFlow(row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div style="margin-top:12px; text-align:right">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10,20,50,100]"
          v-model:current-page="flowQuery.pageNum"
          v-model:page-size="flowQuery.pageSize"
          :total="flowTotal"
          @size-change="loadFlows"
          @current-change="loadFlows"
        />
      </div>
      
      <template #footer>
        <el-button @click="flowSelector.visible = false">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { pageDevice, getDevice, addDevice, updateDevice, delDevice } from '@/api/iot/device'
import { treeDeviceGroup, listDeviceGroup } from '@/api/iot/device-group'
import { pageProduct } from '@/api/iot/product'
import { getNodeRedFlows, getNodeRedFlow } from '@/api/iot/nodered'
import type { IotDeviceVO, IotDeviceQuery, IotDeviceForm } from '@/api/iot/device/types'
import type { IotDeviceGroupVO } from '@/api/iot/device-group/types'
import type { IotProductVO, IotProductQuery } from '@/api/iot/product/types'

const query = reactive<IotDeviceQuery>({ 
  pageNum: 1, 
  pageSize: 10, 
  deviceName: '', 
  deviceCode: '', 
  productId: undefined, 
  groupId: undefined, 
  deviceStatus: '' 
})
const rows = ref<IotDeviceVO[]>([])
const total = ref(0)

const dialog = reactive({ visible: false, isEdit: false })
const form = ref<IotDeviceForm>({})
const formRef = ref()
const buttonLoading = ref(false)

// 新增：表单页签
const deviceFormTab = ref<'basic' | 'protocol'>('basic')

const rules = reactive({
  deviceName: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
  deviceCode: [{ required: true, message: '设备编码不能为空', trigger: 'blur' }],
  productId: [{ required: true, message: '请选择产品', trigger: 'change' }]
})

const groupOptions = ref<IotDeviceGroupVO[]>([])

// 添加产品选项
const productOptions = ref<IotProductVO[]>([])

// 产品选择相关
const productSelector = reactive({ visible: false })
const productQuery = reactive<IotProductQuery>({
  pageNum: 1,
  pageSize: 10,
  productName: '',
  productCode: '',
  deviceType: ''
})
const productRows = ref<IotProductVO[]>([])
const productTotal = ref(0)

// 选中的产品名称（用于显示）
const selectedProductName = computed(() => {
  if (form.value.productId) {
    // 首先尝试从已加载的产品列表中查找
    if (productRows.value.length > 0) {
      const product = productRows.value.find(p => p.productId === form.value.productId)
      if (product) {
        return product.productName
      }
    }
    
    // 如果产品列表中没有，尝试从设备数据中获取产品名称
    if (form.value.productName) {
      return form.value.productName
    }
    
    // 如果都没有，显示产品ID
    return `产品ID: ${form.value.productId}`
  }
  return ''
})

const selectedFlowName = computed(() => {
  if (!form.value.flowId) return ''
  const f = flowRows.value.find(it => it.flowId === form.value.flowId) || flowOptions.value.find(it => it.flowId === form.value.flowId)
  return f ? f.flowName : ''
})

async function ensureFlowName(flowId?: number) {
  if (!flowId) return
  const exists = flowRows.value.some(it => it.flowId === flowId) || flowOptions.value.some(it => it.flowId === flowId)
  if (exists) return
  try {
    const { data } = await getNodeRedFlow(String(flowId))
    if (data) {
      // 缓存到 options 以便 computed 能找到
      flowOptions.value = [...flowOptions.value, data]
    }
  } catch {}
}

const flowOptions = ref<any[]>([])
 
 // 设备协议编辑器状态
 const deviceProtoEditor = reactive({
   visible: false,
   mqtt: { brokerUrl: '', clientId: '', username: '', password: '', publishTopic: '', subscribeTopic: '', qos: 0 },
   tcp: { host: '', port: 0, timeoutMs: 0 },
   modbus: { type: 'tcp', host: '', port: 0, portName: '', baudRate: 0, dataBits: 0, stopBits: 0, parity: 0, timeoutMs: 0, points: [] as any[] },
   http: { baseUrl: '', path: '', method: '' }
 })

 // 各协议覆盖默认值（设备级，仅覆盖常用字段）
 const defaultDeviceOverride: Record<string, any> = {
   mqtt: { brokerUrl: 'mqtt://127.0.0.1:1883', clientId: 'device-001', username: '', password: '', publishTopic: '', subscribeTopic: '', qos: 0 },
   tcp: { host: '127.0.0.1', port: 502, timeoutMs: 2000 },
   modbus: { type: 'tcp', host: '127.0.0.1', port: 502, timeoutMs: 2000, portName: 'COM1', baudRate: 9600, dataBits: 8, stopBits: 1, parity: 0, points: [] },
   http: { baseUrl: 'http://127.0.0.1:8080', path: '/api/data', method: 'POST' }
 }

 const deviceProtocolJsonPlaceholder = computed(() => {
   if (!form.value.protocolType) return ''
   if (form.value.protocolType === 'mqtt') {
     return '覆盖示例: {"brokerUrl":"mqtt://127.0.0.1:1883","clientId":"dev-01"}'
   } else if (form.value.protocolType === 'tcp') {
     return '覆盖示例: {"host":"10.0.0.10","port":502}'
   } else if (form.value.protocolType === 'modbus') {
     return '覆盖示例: {"type":"tcp","host":"10.0.0.10","port":502}'
   } else if (form.value.protocolType === 'http') {
     return '覆盖示例: {"baseUrl":"http://api","path":"/push","method":"POST"}'
   }
   return ''
 })
 
 function openDeviceProtoEditor() {
   try {
     const obj = form.value.protocolConfigOverride ? JSON.parse(form.value.protocolConfigOverride) : {}
     if (form.value.protocolType === 'mqtt') deviceProtoEditor.mqtt = { ...defaultDeviceOverride.mqtt, ...obj }
     else if (form.value.protocolType === 'tcp') deviceProtoEditor.tcp = { ...defaultDeviceOverride.tcp, ...obj }
     else if (form.value.protocolType === 'modbus') {
       const parsed = { ...defaultDeviceOverride.modbus, ...obj }
       parsed.points = Array.isArray(obj.points) ? obj.points : []
       deviceProtoEditor.modbus = parsed
     }
     else if (form.value.protocolType === 'http') deviceProtoEditor.http = { ...defaultDeviceOverride.http, ...obj }
   } catch {}
   deviceProtoEditor.visible = true
 }
 
 function addModbusPoint() {
   deviceProtoEditor.modbus.points.push({ code: '', function: 'holding', slaveId: 1, offset: 0, quantity: 1, periodSec: 5 })
 }
 function removeModbusPoint(idx: number) {
   deviceProtoEditor.modbus.points.splice(idx, 1)
 }
 
 function applyDeviceProtoEditor() {
   if (form.value.protocolType === 'mqtt') form.value.protocolConfigOverride = JSON.stringify(deviceProtoEditor.mqtt)
   else if (form.value.protocolType === 'tcp') form.value.protocolConfigOverride = JSON.stringify(deviceProtoEditor.tcp)
   else if (form.value.protocolType === 'modbus') {
     // 简单校验
     if (!deviceProtoEditor.modbus.points || deviceProtoEditor.modbus.points.length === 0) {
       ElMessage.error('请至少配置一个 Modbus 点位')
       return
     }
     form.value.protocolConfigOverride = JSON.stringify({
       type: deviceProtoEditor.modbus.type,
       host: deviceProtoEditor.modbus.host,
       port: deviceProtoEditor.modbus.port,
       timeoutMs: deviceProtoEditor.modbus.timeoutMs,
       portName: deviceProtoEditor.modbus.portName,
       baudRate: deviceProtoEditor.modbus.baudRate,
       dataBits: deviceProtoEditor.modbus.dataBits,
       stopBits: deviceProtoEditor.modbus.stopBits,
       parity: deviceProtoEditor.modbus.parity,
       points: deviceProtoEditor.modbus.points
     })
   }
   else if (form.value.protocolType === 'http') form.value.protocolConfigOverride = JSON.stringify(deviceProtoEditor.http)
   deviceProtoEditor.visible = false
 }

 // 切换协议类型时，如覆盖 JSON 为空，则预填默认覆盖值
 watch(() => form.value.protocolType, (type) => {
   if (!type) return
   if (!form.value.protocolConfigOverride || form.value.protocolConfigOverride.trim() === '') {
     const def = defaultDeviceOverride[type]
     if (def) form.value.protocolConfigOverride = JSON.stringify(def)
   }
 })

const initFormData: IotDeviceForm = {
  deviceId: undefined,
  deviceName: '',
  deviceCode: '',
  productId: undefined,
  productName: '',
  groupId: undefined,
  deviceIp: '',
  devicePort: undefined,
  deviceStatus: '0',
  location: '',
  longitude: undefined,
  latitude: undefined,
  installTime: '',
  remark: '',
  flowId: undefined
}

async function load() {
  try {
    const response = await pageDevice(query)
    
    if (response && response.rows && Array.isArray(response.rows)) {
      rows.value = response.rows
      total.value = response.total || 0
    } else {
      rows.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('加载设备数据失败：', error)
    ElMessage.error('加载设备数据失败')
  }
}

function reset() {
  query.deviceName = ''
  query.deviceCode = ''
  query.productId = undefined
  query.groupId = undefined
  query.deviceStatus = ''
  query.pageNum = 1
  query.pageSize = 10
  load()
}

async function loadGroupOptions() {
  try {
    const groupRes = await treeDeviceGroup()
    
    if (groupRes && groupRes.rows && Array.isArray(groupRes.rows)) {
      groupOptions.value = groupRes.rows
    } else if (Array.isArray(groupRes)) {
      groupOptions.value = groupRes
    } else if (groupRes && groupRes.data && Array.isArray(groupRes.data)) {
      groupOptions.value = groupRes.data
    } else {
      // 如果树形接口失败，尝试列表接口
      try {
        const listRes = await listDeviceGroup({ pageNum: 1, pageSize: 1000 })
        
        if (listRes && Array.isArray(listRes)) {
          groupOptions.value = listRes
        } else if (listRes && listRes.rows && Array.isArray(listRes.rows)) {
          groupOptions.value = listRes.rows
        } else if (listRes && listRes.data && Array.isArray(listRes.data)) {
          groupOptions.value = listRes.data
        } else {
          groupOptions.value = []
        }
      } catch (listError) {
        groupOptions.value = []
      }
    }
  } catch (error) {
    console.error('加载分组选项失败：', error)
    groupOptions.value = []
  }
}

// 产品选择相关函数
async function loadProducts() {
  try {
    const response = await pageProduct(productQuery)
    
    if (response && response.rows && Array.isArray(response.rows)) {
      productRows.value = response.rows
      productTotal.value = response.total || 0
    } else {
      productRows.value = []
      productTotal.value = 0
    }
  } catch (error) {
    console.error('加载产品数据失败：', error)
    ElMessage.error('加载产品数据失败')
  }
}

// 添加加载产品选项的函数
async function loadProductOptions() {
  try {
    const response = await pageProduct({ pageNum: 1, pageSize: 1000 })
    
    if (response && response.rows && Array.isArray(response.rows)) {
      productOptions.value = response.rows
    } else {
      productOptions.value = []
    }
  } catch (error) {
    console.error('加载产品选项失败：', error)
    productOptions.value = []
  }
}

async function loadFlowOptions() {
  try {
    const res = await getNodeRedFlows({})
    const data = (res?.data && Array.isArray(res.data)) ? res.data : (Array.isArray(res) ? res : [])
    flowOptions.value = data
  } catch (e) {
    flowOptions.value = []
  }
}

// 规则选择相关状态与函数
const flowSelector = reactive<{ visible: boolean }>({ visible: false })
const flowQuery = reactive<{ flowName: string; pageNum: number; pageSize: number }>({ flowName: '', pageNum: 1, pageSize: 10 })
const flowRows = ref<any[]>([])
const flowTotal = ref(0)

function resetProductQuery() {
  productQuery.productName = ''
  productQuery.productCode = ''
  productQuery.deviceType = ''
  productQuery.pageNum = 1
  productQuery.pageSize = 10
  loadProducts()
}

function openProductSelector() {
  productSelector.visible = true
  loadProducts()
}

function selectProduct(row: IotProductVO) {
  form.value.productId = row.productId
  productSelector.visible = false
  ElMessage.success(`已选择产品：${row.productName}`)
}

function openCreate() {
  dialog.visible = true
  dialog.isEdit = false
  form.value = JSON.parse(JSON.stringify(initFormData))
  deviceFormTab.value = 'basic'
}

function openEdit(row: IotDeviceVO) {
  dialog.visible = true
  dialog.isEdit = true
  form.value = { ...row }
  deviceFormTab.value = 'basic'
}

function closeDialog() {
  dialog.visible = false
  resetForm()
}

function cancel() {
  dialog.visible = false
  resetForm()
}

function resetForm() {
  form.value = JSON.parse(JSON.stringify(initFormData))
  deviceFormTab.value = 'basic'
  nextTick(() => {
    formRef.value?.resetFields()
  })
}

async function doSubmit() {
  if (!formRef.value) return
  
  await formRef.value.validate()
  buttonLoading.value = true
  
  try {
  if (dialog.isEdit) {
      await updateDevice(form.value)
  } else {
      await addDevice(form.value)
  }
  ElMessage.success('保存成功')
  dialog.visible = false
  load()
  } catch (error) {
    console.error('保存失败:', error)
  } finally {
    buttonLoading.value = false
  }
}

async function doRemove(row: IotDeviceVO) {
  await ElMessageBox.confirm(`确认删除设备「${row.deviceName}」吗？`, '提示', { type: 'warning' })
  await delDevice(row.deviceId!)
  ElMessage.success('已删除')
  load()
}

function openFlowSelector() {
  flowSelector.visible = true
  loadFlows()
}

function resetFlowQuery() {
  flowQuery.flowName = ''
  flowQuery.pageNum = 1
  flowQuery.pageSize = 10
  loadFlows()
}

async function loadFlows() {
  try {
    const params: any = { pageNum: flowQuery.pageNum, pageSize: flowQuery.pageSize }
    if (flowQuery.flowName) params.flowName = flowQuery.flowName
    const res = await getNodeRedFlows(params)
    const data = res?.data?.records || []
    const totalCount = res?.data?.total || 0
    flowRows.value = Array.isArray(data) ? data : []
    flowTotal.value = totalCount
  } catch (e) {
    flowRows.value = []
    flowTotal.value = 0
  }
}

function selectFlow(row: any) {
  form.value.flowId = row.flowId
  flowSelector.visible = false
  ElMessage.success(`已选择规则：${row.flowName}`)
}

onMounted(() => {
  load()
  loadGroupOptions()
  loadProductOptions() // 添加这行
  loadFlowOptions()
})

// 当加载设备详情后，确保规则名称可显示
watch(() => form.value.flowId, (val) => { ensureFlowName(val as any) })
</script>
